﻿using System;
using System.Web;
using System.Collections.Generic;
using System.Linq;
using System.Web.SessionState;

using LDAP.Utility;
using LDAP.Web;
using LDAP.Entity;
using LDAP.BLL;
using System.Collections;

namespace LDAP.Handler
{
    public class AttendanceMgmt : BaseWebHandler, IRequiresSessionState, IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            base.ProcessRequest(context);
            if (!base.IsSuperAdministrator() && !base.IsAngel())
            {
                base.Response.Write(new JsonTransfer().SetApiFailed("没有权限, 不要乱来，背后有人盯着你呢！"));
                base.Response.End();
            }
            switch (base.Action)
            {
                case "setCalendar":
                    this.SetCalendar();
                    break;
                case "addAngels":
                    this.AddAngels();
                    break;
                case "delAngel":
                    this.DeleteAngel();
                    break;
                case "updateAngelServiceDept":
                    this.UpdateAngelServiceDepartment();
                    break;
                case "approveTicket":
                    this.ApproveTicket();
                    break;
                case "getUserAccessRecord":
                    this.GetUserAccessRecord();
                    break;
                case "generalReport":
                    this.GeneralReport();
                    break;
                default:
                    base.Response.Write("hello world!");
                    break;
            }
            base.Response.End();
        }

        // Methods
        public void AddAngels()
        {
            IEnumerable<string> source = Tools.Web.Request.GetFormString("codes").Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).Distinct();
            JsonTransfer transfer = new JsonTransfer();
            if (source.Count() == 0)
            {
                transfer.SetApiFailed("乖，别闹了，赶紧先选个人");
                Response.Write(transfer);
                return;
            }
            
            string message = "";
            List<User> userList = BizUser.AllUser(ref message);
            List<Angel> list = BizAngel.GetAll().ToList();
            int num = 0;

            foreach (string angel in source) {
                if (!list.Exists(l => l.Id.ToLower() == angel.ToLower()))
                {
                    Angel temp = new Angel
                    {
                        Id = angel,
                        UserName = userList.First(l => l.Id.ToLower() == angel.ToLower()).UserName
                    };
                    num += BizAngel.Add(temp);
                }
            }
            transfer.Add("count", num);
            transfer.SetApiSuccess();
            Response.Write(transfer);
        }

        public void ApproveTicket()
        {
            long id = Tools.Web.Request.GetFormLong("id", 0);
            int status = Tools.Web.Request.GetFormInt("status", 0);
            string comment = Tools.Web.Request.GetFormString("comment");
            int type = Tools.Web.Request.GetFormInt("type", 0);
            string duration = Tools.Web.Request.GetFormString("duration");
            JsonTransfer transfer = new JsonTransfer();
            if (id <= 0)
            {
                transfer.SetApiFailed("");
                Response.Write(transfer);
                return;
            }

            Exceptionform ef = BizExceptionform.GetByKey(id);
            if (ef == null || ef.Status != 0)
            {
                transfer.SetApiFailed("");
                Response.Write(transfer);
                return;
            }

            string[] source = BizAngel.GetByKey(CurrentUser.Id).Dept.Split(new char[] { ',' });
            bool flag = false;
            foreach (string dept in ef.Dept.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
            {
                if (source.Contains(dept))
                {
                    flag = true;
                    break;
                }
            }

            if (!flag)
            {
                transfer.SetApiFailed("您没有当前单据的审批权限哦~是不是智能权限变了呢？");
                Response.Write(transfer);
                return;
            }
            
            try
            {
                ef.Duration = string.IsNullOrEmpty(duration) ? 0f : ((float)Convert.ToDouble(duration));
            }
            catch (Exception exception)
            {
                transfer.SetError(exception.Message);
                transfer.SetApiFailed("时长格式出错啦，再确认下输错了没~~");
                Response.Write(transfer);
                return;
            }

            ef.Status = status;
            ef.PassUserId = base.CurrentUser.Id;
            ef.PassTime = DateTime.Now;
            ef.Comment = Tools.StringUtil.RemoveUnsafeHtml(comment);
            if (ef.Status == 100)
            {
                ef.Type = type;
            }
            BizExceptionform.Update(ef);
            transfer.Add("ef", ef);
            transfer.SetApiSuccess();
            Response.Write(transfer);
        }

        public void DeleteAngel()
        {
            string id = Tools.Web.Request.GetFormString("id");
            JsonTransfer transfer = new JsonTransfer();
            if (BizAngel.Delete(id) > 0)
            {
                transfer.SetApiSuccess();
            }
            else
            {
                transfer.SetApiFailed("");
            }
            Response.Write(transfer);
        }

        public void GeneralReport()
        {
            int year = Tools.Web.Request.GetFormInt("year", DateTime.Now.Year);
            int month = Tools.Web.Request.GetFormInt("month", DateTime.Now.Month);
            List<string> list = Tools.Web.Request.GetFormString("depts").Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();

            JsonTransfer transfer = new JsonTransfer();
            if (list.Count == 0)
            {
                transfer.SetApiFailed("要选择部门范围哦~");
                Response.Write(transfer);
                return;
            }

            DateTime date = new DateTime(year, month, 1);
            MonthSchedule schedule = BizMonthSchedule.GetByDate(date);
            if (schedule == null)
            {
                transfer.SetApiFailed("您选的月份没有设置工作日，赶紧找黄总处理下~");
                Response.Write(transfer);
                return;
            }
            string message = string.Empty;
            List<User> allUser = BizUser.AllUser(ref message);
            List<User> userList = new List<User>();

            foreach (User user in allUser)
            {
                foreach (string dept in user.DeptName.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) {
                    if (list.Exists(l => l.ToLower() == dept.ToLower())) {
                        userList.Add(user);
                        break;
                    }
                }
            }

            string userIds = string.Join(",", userList.Select(l=>l.Id).ToArray());
            transfer.Add("scheduleList", BizSchedule.GetAll().Where(l => userList.Exists(q => q.Id == l.Id)));
            transfer.Add("specialList",BizSpecialschedule.GetAll().Where(l => userList.Exists(q => q.Id == l.UserId)));
            transfer.Add("formList", BizExceptionform.GetByUserList(userIds, date, date.AddMonths(1).AddDays(-1)));
            transfer.Add("recordList", BizAccessrecord.GetUserListAccessRecord(userIds, date.AddDays(-1), date.AddMonths(1)));
            
            TimeSpan span = (TimeSpan)(date.AddMonths(1) - date);
            transfer.Add("workdays", span.Days - schedule.Weekend.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Length);
            transfer.Add("weekend", schedule.Weekend);
            transfer.Add("maxDay", date.AddMonths(1).AddDays(-1).Day);
            transfer.Add("list", userList.OrderBy(l=>l.Id));
            Response.Write(transfer);
        }

        public void GetUserAccessRecord()
        {
            string startTime = Tools.Web.Request.GetQueryString("startTime");
            string endTime = Tools.Web.Request.GetQueryString("endTime");
            string userId = Tools.Web.Request.GetQueryString("userId");

            DateTime start = Convert.ToDateTime(startTime).AddDays(-1);

            IList<Hashtable> list = BizAccessrecord.GetUserAccessRecord(userId, start, Convert.ToDateTime(endTime).AddDays(1));
            JsonTransfer transfer = new JsonTransfer();
            transfer.Add("list", list);
            transfer.Add("schedule", BizSchedule.GetByKey(userId));
            transfer.Add("special", BizSpecialschedule.GetByKey(base.CurrentUser.Id, start, start.AddMonths(1)));
            transfer.SetApiSuccess();
            Response.Write(transfer);
        }

        public void SetCalendar()
        {
            int year = Tools.Web.Request.GetFormInt("year", 0);
            int month = Tools.Web.Request.GetFormInt("month", 0);
            if (new DateTime(year, month, 1) <= DateTime.Today)
            {
                BreakResponse("参数异常，请刷新页面再重试");
            }
            string days = Tools.Web.Request.GetFormString("days");
            MonthSchedule schedule = new MonthSchedule
            {
                Date = new DateTime(year, month, 1),
                Weekend = days
            };
            MonthSchedule entry = schedule;
            JsonTransfer transfer = new JsonTransfer();
            if (BizMonthSchedule.Add(entry) > 0)
            {
                transfer.SetApiSuccess();
            }
            else
            {
                transfer.SetApiFailed("");
            }
            Response.Write(transfer);
        }

        public void UpdateAngelServiceDepartment()
        {
            string id = Tools.Web.Request.GetFormString("id");
            string dept = Tools.Web.Request.GetFormString("dept");
            JsonTransfer transfer = new JsonTransfer();
            Angel byKey = BizAngel.GetByKey(id);
            if (id == null)
            {
                transfer.SetApiFailed("星星都会坠落，何况天使？刷新页面看看新的天使有哪些..");
                Response.Write(transfer);
                return;
            }

            byKey.Dept = "," + dept + ",";
            if (BizAngel.Update(byKey) > 0)
            {
                transfer.SetApiSuccess();
            }
            else
            {
                transfer.SetApiFailed("");
            }
            Response.Write(transfer);
        }
    }
}